package exsun.jt808.data.util;

import com.google.common.base.Stopwatch;
import org.apache.commons.net.ftp.FTP;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPFile;
import org.apache.commons.net.ftp.FTPReply;
import org.jetbrains.annotations.NotNull;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.StopWatch;


import java.io.*;
import java.util.Arrays;
import java.util.List;
import java.util.UUID;
import java.util.stream.Collectors;

@Component
public class FtpUtils {
    private final static Logger logger = LoggerFactory.getLogger(FtpUtils.class);


    public static FTPClient ftpClient;

    private static String host;

    private static int port;

    private  static  String userName;

    private static  String passWord;

    private static  int timeOut;

    public static void setFtpInfo(String ipHost, int ftpPort, String username, String password,  int connectTimeOut )
    {
        host = ipHost;
        port = ftpPort;
        userName = username;
        passWord = password;
        timeOut = connectTimeOut;
    }

    /**
     * 初始化连接
     */
    public static void connect() {
            ftpClient = new FTPClient();
            try {
                //连接ftp服务器
                ftpClient.setConnectTimeout(timeOut);
                ftpClient.connect(host, port);// 连接FTP服务器
                // 如果采用默认端口，可以使用ftp.connect(host)的方式直接连接FTP服务器
                ftpClient.login(userName, passWord);// 登录
                logger.info("ftp登录成功---");
            } catch (Exception ex) {
                logger.info("ftp登录失败---" + ex.toString());
            }
    }

    /**
     * 检查ftp连接状态，若断开则重连
     * @throws IOException
     */
    public static void reconnect() {
        synchronized (ftpClient) {
                    try {
                            ftpClient.disconnect();
                            FtpUtils.connect();
                            logger.info("重连ftp成功");
                    } catch (Exception e) {
                        logger.error(e.toString());
                        logger.error("重连FTP失败");
                    }
        }
    }

    /**
     * 切换目录
     * @param basePath
     * @param filePath
     */
    public static void changeWorkingDirectory(String basePath,String absBasePath ,String filePath,boolean reConnect)
    {
//        ftpClient = new FTPClient();
        synchronized (ftpClient) {
            try {
                //FtpUtils.checkAndReconnect();
                String curForder = ftpClient.printWorkingDirectory();
                logger.info("ftp当前目录:" +  ftpClient.printWorkingDirectory());
                if (!curForder.equals(absBasePath))
                {
                    String ftpforder = curForder.replaceAll(absBasePath,"");
                    logger.info("未回归根目录，ftp目录：" + ftpforder);
                    changeToRoot("",ftpforder,reConnect);
                }
                if (!ftpClient.changeWorkingDirectory(basePath + filePath)) {
                    //如果目录不存在创建目录
                    String finalPath = basePath + filePath;
                    String[] dirs = finalPath.split("/");
                    String tempPath = "";
                    for (String dir : dirs) {
                        if (null == dir || "".equals(dir)) continue;
                        tempPath = dir;
                        if (!ftpClient.changeWorkingDirectory(tempPath)) {
                            if (!ftpClient.makeDirectory(tempPath)) {
                            } else {
                                ftpClient.changeWorkingDirectory(tempPath);
                            }
                        }
                    }
                }
                //设置上传文件的类型为二进制类型
                ftpClient.setFileType(FTP.BINARY_FILE_TYPE);
                ftpClient.enterLocalPassiveMode();
                logger.info("ftp切换目录成功:" +  ftpClient.printWorkingDirectory());
            } catch (Exception ex) {
                if (!reConnect) {
                    reconnect();
                    changeWorkingDirectory(basePath, absBasePath,filePath,true);
                }
                logger.error("切换目录失败--" + ex.toString());
            }
        }
    }

    /**
     * 文件存储
     */
    public static  boolean storageFile(String filename, byte[] data,boolean reConnect)
    {
//        ftpClient = new FTPClient();
        synchronized (ftpClient) {
            try {
                StopWatch stopwatch = new StopWatch();
                stopwatch.start();
                InputStream inputStream = new ByteArrayInputStream(data);
                boolean result = ftpClient.storeFile(filename, inputStream);
                stopwatch.stop();
                logger.info("ftp上传耗时(ms)--" + stopwatch.getLastTaskTimeMillis());
                inputStream.close();
                return result;
            } catch (Exception exception) {
                if (!reConnect) {
                    reconnect();
                    storageFile(filename, data,true);
                }
                logger.error("存储文件失败--" +  exception.toString());
            }
            return false;
        }
    }


    /**
     * 回归至根目录
     * @param basePath
     * @param filePath
     * @return
     */
    public  static  boolean changeToRoot(String basePath, String filePath, boolean reConnect)
    {
        try {
            String finalPath = basePath + filePath;
            List<String> pathList = Arrays.asList(finalPath.split("/")).stream().filter(x -> x != null && !x.isEmpty()).collect(Collectors.toList());
            for (String path : pathList
            ) {
                ftpClient.changeToParentDirectory();
            }
            return true;
        }
        catch (Exception ex)
        {
            if (!reConnect) {
                reconnect();
                changeToRoot(basePath, filePath, true);
            }
            logger.error("切回目录失败" + ex.toString());
            return  false;
        }
    }





    public static String upLoadFtp(@NotNull String ftpIp, @NotNull int ftpPort, @NotNull String ftpUserName,
                                   @NotNull String ftpPassWord, @NotNull String ftpFilepath, @NotNull File localFile) {
        //创建客户端对象
        FTPClient ftp = new FTPClient();
        InputStream local = null;
        String ftpFileName = null;
        try {
            //连接ftp服务器
            ftp.connect(ftpIp, ftpPort);
            //登录
            ftp.login(ftpUserName, ftpPassWord);
            //设置上传路径
            String path = ftpFilepath;
            //检查上传路径是否存在 如果不存在返回false
            boolean flag = ftp.changeWorkingDirectory(path);
            if (!flag) {
                //创建上传的路径  该方法只能创建一级目录，在这里如果/home/ftpuser存在则可创建image
                ftp.makeDirectory(path);
            }
            //指定上传路径
            ftp.changeWorkingDirectory(path);
            //指定上传文件的类型  二进制文件
            ftp.enterLocalPassiveMode();
            ftp.setFileType(FTP.BINARY_FILE_TYPE);
            //读取本地文件
            local = new FileInputStream(localFile);
            //第一个参数是文件名
            String fileName = localFile.getName();
            ftpFileName = UUID.randomUUID().toString() + fileName.substring(fileName.lastIndexOf("."));
            ftp.storeFile(ftpFileName, local);
            return ftpFileName;
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                //关闭文件流
                local.close();
                //退出
                ftp.logout();
                //断开连接
                ftp.disconnect();
            } catch (IOException e) {
                e.printStackTrace();
                return null;
            }
        }
        return ftpFileName;
    }



    /**
     * Description: 向FTP服务器上传文件
     *
     * @param host     FTP服务器hostname
     * @param port     FTP服务器端口
     * @param username FTP登录账号
     * @param password FTP登录密码
     * @param basePath FTP服务器基础目录
     * @param filePath FTP服务器文件存放路径。例如分日期存放：/2015/01/01。文件的路径为basePath+filePath
     * @param filename 上传到FTP服务器上的文件名
     * @param input    输入流
     * @return 成功返回true，否则返回false
     */
    public static boolean uploadFile(String host, int port, String username, String password, String basePath,
                                     String filePath, String filename, InputStream input, int timeOut) {
        boolean result = false;
        FTPClient ftp = new FTPClient();
        try {
            int reply;
            ftp.setConnectTimeout(timeOut);
            ftp.connect(host, port);// 连接FTP服务器
            // 如果采用默认端口，可以使用ftp.connect(host)的方式直接连接FTP服务器
            ftp.login(username, password);// 登录
            reply = ftp.getReplyCode();
            if (!FTPReply.isPositiveCompletion(reply)) {
                ftp.disconnect();
                return result;
            }
            //切换到上传目录
            //linux系统的ftp只能逐级的创建文件目录
            if (!ftp.changeWorkingDirectory(basePath + filePath)) {
                //如果目录不存在创建目录
                String finalPath = basePath + filePath;
                String[] dirs = finalPath.split("/");
                String tempPath = "";
                for (String dir : dirs) {
                    if (null == dir || "".equals(dir)) continue;
                    tempPath = dir;
                    if (!ftp.changeWorkingDirectory(tempPath)) {
                        if (!ftp.makeDirectory(tempPath)) {
                             return result;
                        } else {
                            ftp.changeWorkingDirectory(tempPath);
                        }
                    }
                }
            }
            //设置上传文件的类型为二进制类型
            ftp.setFileType(FTP.BINARY_FILE_TYPE);
            ftp.enterLocalPassiveMode();
            //上传文件
            if (!ftp.storeFile(filename, input)) {
                return result;
            }
            input.close();
            ftp.logout();
            result = true;
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (ftp.isConnected()) {
                try {
                    ftp.disconnect();
                } catch (IOException ioe) {
                }
            }
        }
        return result;
    }

    public static boolean uploadFile(String host, int port, String username, String password, String basePath,
                                     String filePath, String filename, byte[] data, int timeOut)throws Exception{
        InputStream inputStream = new ByteArrayInputStream(data);
        boolean result = uploadFile(host,port,username,password,basePath,filePath,filename,inputStream, timeOut);
        inputStream.close();
        return result;
    }

    /**
     * Description: 从FTP服务器下载文件
     *
     * @param host       FTP服务器hostname
     * @param port       FTP服务器端口
     * @param username   FTP登录账号
     * @param password   FTP登录密码
     * @param remotePath FTP服务器上的相对路径
     * @param fileName   要下载的文件名
     * @param localPath  下载后保存到本地的路径
     * @return
     */
    public static boolean downloadFile(String host, int port, String username, String password, String remotePath,
                                       String fileName, String localPath, int timeOut) {
        boolean result = false;
        FTPClient ftp = new FTPClient();
        try {
            int reply;
            ftp.setConnectTimeout(timeOut);
            ftp.connect(host, port);
            // 如果采用默认端口，可以使用ftp.connect(host)的方式直接连接FTP服务器
            ftp.login(username, password);// 登录
            reply = ftp.getReplyCode();
            if (!FTPReply.isPositiveCompletion(reply)) {
                ftp.disconnect();
                return result;
            }
            ftp.changeWorkingDirectory(remotePath);// 转移到FTP服务器目录
            FTPFile[] fs = ftp.listFiles();
            for (FTPFile ff : fs) {
                if (ff.getName().equals(fileName)) {
                    File localFile = new File(localPath + "/" + ff.getName());

                    OutputStream is = new FileOutputStream(localFile);
                    ftp.retrieveFile(ff.getName(), is);
                    is.close();
                }
            }
            ftp.logout();
            result = true;
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (ftp.isConnected()) {
                try {
                    ftp.disconnect();
                } catch (IOException ioe) {
                }
            }
        }
        return result;
    }

    /**
     * Description: 从FTP服务器下载文件
     *
     * @param host       FTP服务器hostname
     * @param port       FTP服务器端口
     * @param username   FTP登录账号
     * @param password   FTP登录密码
     * @param remotePath FTP服务器上的相对路径
     * @param fileName   要下载的文件名
     * @param localPath  下载后保存到本地的路径
     * @return
     *//**
     * Description: 从FTP服务器下载文件
     *
     * @param host       FTP服务器hostname
     * @param port       FTP服务器端口
     * @param username   FTP登录账号
     * @param password   FTP登录密码
     * @param remotePath FTP服务器上的相对路径
     * @param fileName   要下载的文件名
     * @return
     */
    public static byte[] downloadFile(String host, int port, String username, String password, String remotePath, String fileName, int timeOut) {
        byte[] buffer = null;
        FTPClient ftp = new FTPClient();
        try {
            int reply;
            ftp.setConnectTimeout(timeOut);
            ftp.connect(host, port);
            // 如果采用默认端口，可以使用ftp.connect(host)的方式直接连接FTP服务器
            ftp.login(username, password);// 登录
            ftp.enterLocalPassiveMode();
            reply = ftp.getReplyCode();
            if (!FTPReply.isPositiveCompletion(reply)) {
                ftp.disconnect();
                return null;
            }
            ftp.changeWorkingDirectory(remotePath);// 转移到FTP服务器目录
            InputStream in = ftp.retrieveFileStream(fileName);
            buffer = toByteArray(in);
            in.close();
            ftp.logout();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (ftp.isConnected()) {
                try {
                    ftp.disconnect();
                } catch (IOException ioe) {
                }
            }
        }
        return buffer;
    }

    public static byte[] toByteArray(InputStream input) throws IOException {
        ByteArrayOutputStream output = new ByteArrayOutputStream();
        byte[] buffer = new byte[4096];
        int n = 0;
        while (-1 != (n = input.read(buffer))) {
            output.write(buffer, 0, n);
        }
        return output.toByteArray();
    }

    public static void main(String[] args) throws Exception{
        connect();
    }


}
